﻿
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace CommonTagTime.PagerControl.stylePager2
{
    [DefaultProperty("Text")]
    [ToolboxData("<{0}:stylePager2 runat=server></{0}:stylePager2>")]
    public class stylePager2 : WebControl
    {
        #region Control

        int countPageIndex = 4;
        int indexViewAll = 1;
        int indexPageSizeLabel = 3;
        int indexPageSizeControl = 4;

        int indexSumary = 5;
        int indexPrev = 7;
        int indexPageRange = 8;
        int indexNext = 9;
        private Table tblParent = new Table();
        private string style2ViewAllText = "Xem tất cả";
        private string style2SumaryIndex = "Trang {0} / {1}";
        private string style2PageSizeText = "SP trên trang:";
        private string style2PrevText = "« Trước";
        private string style2NextText = "Sau »";
        private LinkButton style2ButtonPrev = new LinkButton();
        private LinkButton style2ButtonNext = new LinkButton();
        private LinkButton style2ButtonViewAll = new LinkButton();
        private DropDownList drlPageSize = new DropDownList();
        #endregion

        #region Control Properies
        private int _TotalRecord;
        private Boolean _showViewAll = true;
        private Boolean _showPageSize = true;
        [Browsable(false)]
        public int LeftBoundary
        {
            get
            {

                object o = ViewState["LeftBoundary"];
                if (o != null) return (int)o;
                return 1;
            }
            set { ViewState["LeftBoundary"] = value; }
        }
        [Browsable(false)]
        public int RightBoundary
        {
            get
            {

                object o = ViewState["RightBoundary"];
                if (o != null) return (int)o;
                return 1;
            }
            set { ViewState["RightBoundary"] = value; }
        }
        [Browsable(false)]
        public int PageIndex
        {
            get
            {
                object o = ViewState["PageIndex"];
                if (o != null) return (int)o;
                return 1;
            }

            set { ViewState["PageIndex"] = value; }

        }
        [Browsable(false)]
        public int PageSize
        {
            get
            {
                //object o = ViewState["PageSize"];
                //if (o != null) return (int)o;
                try
                {
                    return clsConvert.Int(drlPageSize.SelectedValue.ToString());
                }
                catch
                { 
                }
                return 10;
            }

            set
            {
                try
                {
                    drlPageSize.SelectedValue = value.ToString();
                }
                catch
                {
                }
              //  ViewState["PageSize"] = value;
            }

        }
        [Browsable(false)]
        public int TotalPage
        {

            get
            {

                object o = ViewState["TotalPage"];
                if (o != null) return (int)o;
                return 1;
            }

            set { ViewState["TotalPage"] = value; }

        }
        [Browsable(false)]
        [Description("Total record of result")]
        public int TotalRecord
        {
            get
            {
                return _TotalRecord;
            }
            set
            {
                _TotalRecord = value;
            }
        }

        [Browsable(true)]
        [Description("Show or Hidden control ViewAll")]
        public Boolean ShowViewAll
        {
            get
            {
                return _showViewAll;
            }
            set
            {
                _showViewAll = value;
            }
        }
        [Browsable(true)]
        [Description("Show or Hidden control PageSize")]
        public Boolean ShowPageSize
        {
            get
            {
                return _showPageSize;
            }
            set
            {
                _showPageSize = value;
            }
        }
        #endregion

        #region Delegate
        public delegate void ChangePageSize(object obj, PageSizeChangeEventArgs e);
        public event ChangePageSize PageSizeChanging;
        public delegate void ChangePageIndex(object obj, PageIndexChangeEventArgs e);
        public event ChangePageIndex PageIndexChanging;
        #endregion

        #region Init Control

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

        }
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            InitTableControlFormat2();
        }

        #endregion


        #region Methods
        private void AddCell(ref TableRow tr, TableCell cell, ref int index)
        {
            tr.Controls.AddAt(index, cell);//add cell sumary;
            index++;
        }
        private void InitTableControlFormat2()
        {
            tblParent.Rows.Clear();
            // if (countPageIndex > this.PageSize)
            //    countPageIndex = this.PageSize;
            InitPageSize();
            drlPageSize.ID = this.ID + "_" + "drlPageSize";
            int indexCell = 0;
            TableRow tr = new TableRow();
            TableCell cell = new TableCell();
            cell.Text = string.Empty;
            cell.Attributes.Add("width", "auto");
            //tr.Controls.AddAt(0, cell);//add  empty cell;
            AddCell(ref tr, cell, ref indexCell);
            cell = new TableCell();
            //cell.Width = 100;
            cell.HorizontalAlign = HorizontalAlign.Right;
            cell.VerticalAlign = VerticalAlign.Middle;
            cell.Attributes.Add("class", "viewallss");
            style2ButtonViewAll.Text = style2ViewAllText;
            style2ButtonViewAll.ID = this.ID + "_" + "style2ButtonViewAll";
            style2ButtonViewAll.Click += new EventHandler(style2ButtonViewAll_Click);
            cell.Controls.Add(style2ButtonViewAll);
            if (!ShowViewAll)
                cell.Attributes.Add("style", "display:none");
            //tr.Controls.AddAt(1, cell);//add cell sumary;
            AddCell(ref tr, cell, ref indexCell);
            cell = new TableCell();           
            cell.HorizontalAlign = HorizontalAlign.Center;
            cell.VerticalAlign = VerticalAlign.Middle;
            cell.Attributes.Add("class", "pageline");
            cell.Text = "|";
            if (!ShowViewAll)
                cell.Attributes.Add("style", "display:none");
            AddCell(ref tr, cell, ref indexCell);
            //addd Page Size Label
            cell = new TableCell();
            cell.HorizontalAlign = HorizontalAlign.Left;
            cell.VerticalAlign = VerticalAlign.Middle;
            cell.Text = style2PageSizeText;
            cell.Attributes.Add("class", "pagesizeText");
            if (!ShowPageSize)
                cell.Attributes.Add("style", "display:none");
            AddCell(ref tr, cell, ref indexCell);
            //addd page size Control
            drlPageSize.Attributes.Add("class", "pagesizeControl");
            cell = new TableCell();
            cell.Attributes.Add("class", "pagesizeControlTd");
            cell.Controls.Add(drlPageSize);
            if (!ShowPageSize)
                cell.Attributes.Add("style", "display:none");
            AddCell(ref tr, cell, ref indexCell);
            cell = new TableCell();
            cell.Text = string.Format(style2SumaryIndex, 1, 10);
            cell.HorizontalAlign = HorizontalAlign.Center;
            cell.Attributes.Add("class", "totalpages");
            // tr.Controls.AddAt(2, cell);
            AddCell(ref tr, cell, ref indexCell);

            cell = new TableCell();
            cell.HorizontalAlign = HorizontalAlign.Center;
            cell.VerticalAlign = VerticalAlign.Middle;
            cell.Attributes.Add("class", "pageline");
            cell.Text = "|";
            AddCell(ref tr, cell, ref indexCell);
            ///add link button Prev         
            style2ButtonPrev.Text = style2PrevText;
            style2ButtonPrev.ID = this.ID + "_" + "style2ButtonPrev";
            style2ButtonPrev.Click += new EventHandler(style2ButtonPrev_Click);
            //style2ButtonPrev.CssClass = "arrow";
            cell = new TableCell();
            cell.Attributes.Add("class", "prev");
            cell.HorizontalAlign = HorizontalAlign.Left;
            cell.Controls.Add(style2ButtonPrev);
            //tr.Controls.AddAt(3, cell);
            AddCell(ref tr, cell, ref indexCell);
            cell = new TableCell();
            cell.HorizontalAlign = HorizontalAlign.Left;
            int wCell = 0;
            int addPageIndex = 1;
            while (addPageIndex <= countPageIndex)
            {
                //addd demo open page
                LinkButton style2PageIndex = new LinkButton();
                // style2PageIndex.= "lbtnIndex_1";
                style2PageIndex.Text = addPageIndex.ToString();
                style2PageIndex.CssClass = "pageindexText";
                style2PageIndex.ID = this.ID + "_" + "style2PageIndex_" + addPageIndex.ToString();
                style2PageIndex.Click += new EventHandler(style2PageIndex_Click);
                wCell += 10;
                cell.Controls.Add(style2PageIndex);
                addPageIndex++;
            }
            cell.Attributes.Add("class", "pageindexTextTd");
            //cell.Width = wCell;
            AddCell(ref tr, cell, ref indexCell);
            style2ButtonNext.Text = style2NextText;
            style2ButtonNext.ID = this.ID + "_" + "style2ButtonNext";
            style2ButtonNext.Click += new EventHandler(style2ButtonNext_Click);
            cell = new TableCell();
            cell.Attributes.Add("class", "next");
            cell.HorizontalAlign = HorizontalAlign.Right;
            cell.Controls.Add(style2ButtonNext);
            //tr.Controls.AddAt(3, cell);
            AddCell(ref tr, cell, ref indexCell);


            //tr.Controls.AddAt(4, cell);            
            AddCell(ref tr, cell, ref indexCell);
            tr.Attributes.Add("class","pagingRow");
            tblParent.Rows.Add(tr);
            // tblParent.BorderWidth = 1;
            //  this.Attributes.Add("class", "");
            this.tblParent.Attributes.Add("class", "pagingStyle2");
            this.Controls.Add(tblParent);
        }

        void style2ButtonViewAll_Click(object sender, EventArgs e)
        {
            this.PageIndex = 1;
            this.PageSize = int.MaxValue;
            if (PageSizeChanging != null)
            {
                PageSizeChanging(this, new PageSizeChangeEventArgs(int.MaxValue));
            }
        }
        /// <summary>
        /// Check if current page is the last page
        /// </summary>
        /// <returns></returns>
        public bool IsLastPage()
        {
            if (TotalPage == 0)
                return true;
            if (PageIndex == TotalPage)
                return true;
            return false;
        }
        /// <summary>
        /// Check if current page is the first page
        /// </summary>
        /// <returns></returns>
        public bool IsFirstPage()
        {
            if (TotalPage == 0)
                return true;
            if (PageIndex == 1)
                return true;
            return false;
        }

        protected override void RenderContents(HtmlTextWriter output)
        {
            //this.pnParent.RenderControl(output);
            // this.RenderControl(output
            this.tblParent.RenderControl(output);
        }
        private void InitPageSize()
        {
            //this.drlPageSize.Items.Add(new ListItem("2", "2"));
           // this.drlPageSize.Items.Add(new ListItem("4", "4"));
            this.drlPageSize.Items.Add(new ListItem("12", "12"));
            this.drlPageSize.Items.Add(new ListItem("24", "24"));
            this.drlPageSize.Items.Add(new ListItem("36", "36"));
            this.drlPageSize.Items.Add(new ListItem("72", "72"));
            this.drlPageSize.Items.Add(new ListItem("--All--",int.MaxValue.ToString())); 
            drlPageSize.SelectedIndexChanged += new EventHandler(drlPageSize_SelectedIndexChanged);
            drlPageSize.AutoPostBack = true;
            //try
            //{
            //    drlPageSize.SelectedValue = this.PageSize.ToString();
            //}
            //catch { }
        }
        public void SetPaging(int selectRow, int totalRow)
        {
            // this.PageIndex = pageIndex;           
            this.TotalRecord = totalRow;
            this.TotalPage = this._TotalRecord / this.PageSize;
            if (this._TotalRecord % this.PageSize != 0)
                this.TotalPage++;
            TableCell cell = this.tblParent.Rows[0].Cells[indexPageRange];
            ControlCollection lstControl = cell.Controls;
            int count = 1;
            int cellW = (int)cell.Width.Value;
            int currentIndexPage = this.PageIndex;
            //cacula left and right
            int left = 1;
            int right = countPageIndex;
            SetInitPageData(ref left, ref right);
            this.LeftBoundary = left;
            this.RightBoundary = right;
            int point = left;
            int indexControl = 0;
            while (count <= countPageIndex)
            {
                LinkButton lbtn = null;
                try
                {
                    lbtn = (LinkButton)lstControl[indexControl];
                }
                catch
                { }
                if (lbtn != null)
                {
                    if (count <= (right - left + 1))
                    {
                        lbtn.Attributes.Add("style", "display:");
                        lbtn.Text = point.ToString();
                        if (this.PageIndex == point)
                        {
                            lbtn.CssClass = "pageindexTextActive";
                            lbtn.Attributes.Add("onclick", "javascript:return false;");
                        }
                        else
                        {
                            lbtn.CssClass = "pageindexText";
                            lbtn.Attributes.Add("onclick", "javascript:return true;");
                        }
                       
                    }
                    else
                    {
                        lbtn.Attributes.Add("style", "display:none");
                        cellW = cellW - 10;
                    }
                }
                indexControl++;
                count++;
                point++;
            }
            if (cellW < 0)
                cellW = 10;
           // cell.Width = cellW;
            TableCell cell1 = new TableCell();
            cell1 = this.tblParent.Rows[0].Cells[indexSumary];
            cell1.Text = string.Format(style2SumaryIndex, this.PageIndex, this.TotalPage);
            if (IsFirstPage())
            {
                this.tblParent.Rows[0].Cells[indexPrev].Attributes.Add("style", "display:none");
                this.tblParent.Rows[0].Cells[indexPrev - 1].Attributes.Add("class", "pageline1");
                this.tblParent.Rows[0].Cells[indexPrev - 1].HorizontalAlign = HorizontalAlign.Right;
            }
            else
            {
                this.tblParent.Rows[0].Cells[indexPrev].Attributes.Add("style", "display:");
                this.tblParent.Rows[0].Cells[indexPrev - 1].Attributes.Add("class", "pageline");
                this.tblParent.Rows[0].Cells[indexPrev - 1].HorizontalAlign = HorizontalAlign.Center;
            }
            if (IsLastPage())
                this.tblParent.Rows[0].Cells[indexNext].Attributes.Add("style", "display:none");
            else this.tblParent.Rows[0].Cells[indexNext].Attributes.Add("style", "display:");
            if (!ShowPageSize)
               this.tblParent.Rows[0].Cells[indexViewAll + 1].Attributes.Add("class", "pageline2");
            else this.tblParent.Rows[0].Cells[indexViewAll + 1].Attributes.Add("class", "pageline");
            if (this.TotalPage < 2)
                this.tblParent.Visible = false;

        }
        private void SetInitPageData(ref int left, ref int right)
        {
            if (this.PageIndex == 1)
            {
                left = 1;
                right = left - 1;
                int count = 1;
                while (count <= countPageIndex)
                {
                    right++;
                    count++;
                }
                if (right > TotalPage)
                    right = TotalPage;
                return;
            }
            else if (this.PageIndex == TotalPage)
            {
                right = TotalPage;
                //reset left
                left = right + 1;
                int count = 1;
                while (count <= countPageIndex)
                {
                    left--;
                    count++;
                }
                if (left < 1)
                    left = 1;
                return;
            }
            else
            {
                int mid = (LeftBoundary + RightBoundary) / 2;
                if (PageIndex == mid)
                {
                    left = LeftBoundary;
                    right = RightBoundary;
                    return;
                }
                else if (PageIndex > mid)
                {
                    left = mid;
                    if (left + countPageIndex - 1 > TotalPage)
                        left = TotalPage - countPageIndex + 1;
                    //reset right
                    right = left - 1;
                    int count = 1;
                    while (count <= countPageIndex)
                    {
                        right++;
                        count++;
                    }
                    if (right > TotalPage)
                        right = TotalPage;
                    return;
                }
                else
                {
                    right = mid;
                    if (right < countPageIndex)
                    {
                        right = countPageIndex;
                        if (right >= TotalPage)
                            right = TotalPage;
                    }
                    //reset left
                    left = right + 1;
                    int count = 1;
                    while (count <= countPageIndex)
                    {
                        left--;
                        count++;
                    }
                    if (left < 1)
                        left = 1;
                    return;
                }
            }
        }


        #endregion

        #region Events Handle
        void lbtnPageIndex_Click(object sender, EventArgs e)
        {
            LinkButton lbtn = (LinkButton)sender;
            this.PageIndex = int.Parse(lbtn.Text);
            if (PageIndexChanging != null)
            {
                PageIndexChanging(this, new PageIndexChangeEventArgs(this.PageIndex));
            }
        }

        void lbtnPage_Click(object sender, EventArgs e)
        {
            LinkButton lbtn = (LinkButton)sender;
            this.PageIndex = int.Parse(lbtn.Text);
            if (PageIndexChanging != null)
            {
                PageIndexChanging(this, new PageIndexChangeEventArgs(this.PageIndex));
            }
        }
        void drlPageSize_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.PageSize = int.Parse(drlPageSize.SelectedValue);
            if (PageSizeChanging != null)
            {

                PageSizeChanging(this, new PageSizeChangeEventArgs(this.PageSize));

            }
        }
        void style2ButtonNext_Click(object sender, EventArgs e)
        {
            this.PageIndex = this.PageIndex + 1;
            if (this.PageIndex > TotalPage)
                this.PageIndex = TotalPage;
            if (PageIndexChanging != null)
            {
                PageIndexChanging(this, new PageIndexChangeEventArgs(this.PageIndex));
            }
        }

        void style2PageIndex_Click(object sender, EventArgs e)
        {
            LinkButton lbtn = (LinkButton)sender;
            this.PageIndex = int.Parse(lbtn.Text);
            if (PageIndexChanging != null)
            {
                PageIndexChanging(this, new PageIndexChangeEventArgs(this.PageIndex));
            }
        }

        void style2ButtonPrev_Click(object sender, EventArgs e)
        {
            this.PageIndex = this.PageIndex - 1;
            if (this.PageIndex < 1)
                this.PageIndex = 1;
            if (PageIndexChanging != null)
            {
                PageIndexChanging(this, new PageIndexChangeEventArgs(this.PageIndex));
            }
        }

        #endregion
    }
}
